import axios from 'axios'
import { ElMessage } from 'element-plus'
import { GET_TOKEN } from '@/utils/token'

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 5000
})

// post请求头
// service.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'

// 请求拦截器
service.interceptors.request.use(config => {
  const token = GET_TOKEN()
  if (token) {
    // 给每个请求添加token
    config.headers.token = token
  }
  return config
})

// 响应拦截器
service.interceptors.response.use(res => {
  // console.log(res);
  // 判断状态码，查看token是否过期
  return res.data
}, error => {
  let msg = ''
  const status = error.response.status;
  switch (status) {
    case 401:
      msg = 'TOKEN错误'
      break;
    case 403:
      msg = '无权限'
      break;
    case 404:
      msg = '请求地址错误'
      break;
    case 500:
      msg = '服务器错误'
      break;
    default:
      msg = '网络出现问题'
      break;
  }
  ElMessage.error(msg)
  return Promise.reject(error);
})

export default service